package my.study.jvm;


public class FinalizeEscapeGC {
	public static FinalizeEscapeGC SAVE_HOOK = null;
	
	public void isAlive() {
		System.out.println("yes, I am still alive :)");
	}
	
	@Override
	public void finalize() throws Throwable {
		super.finalize();
		FinalizeEscapeGC.SAVE_HOOK = this;
		System.out.println("finalize method executed!");
	}

	/**
	 * @param args
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException {
		SAVE_HOOK = new FinalizeEscapeGC();
		//对象第一次成功拯救自己
		saveMe();
		
		//对象第二次拯救失败ßß
		saveMe();
		
	}
	
	public static void saveMe() throws InterruptedException {
		SAVE_HOOK = null;
		System.gc();
		
		Thread.sleep(1000);
		
		if (SAVE_HOOK != null) {
			SAVE_HOOK.isAlive();
		} else {
			System.out.println("no, I am dead :(");
		}
	}

}
